package com.zhaoyd.uaademo.service;

import com.zhaoyd.uaademo.api.gitee.entity.GiteeUserInfo;
import com.zhaoyd.uaademo.config.security.integration.IntegrationAuthentication;
import com.zhaoyd.uaademo.core.orm.BaseMapper;
import com.zhaoyd.uaademo.core.orm.BaseService;
import com.zhaoyd.uaademo.entity.SysThirdUser;
import com.zhaoyd.uaademo.enums.LoginType;
import com.zhaoyd.uaademo.mapper.SysThirdUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author zhaoyd
 * @date 2020-11-10 20:42
 */
@Service
public class SysThirdUserService extends BaseService<SysThirdUser> {
    @Resource
    private SysThirdUserMapper sysThirdUserMapper;
    @Resource
    private SysUserService sysUserService;
    @Override
    protected BaseMapper<SysThirdUser> dao() {
        return sysThirdUserMapper;
    }

    public Integer getByThirdUserId(String thirdUserId, String type){
        SysThirdUser queryBean = new SysThirdUser();
        queryBean.setThirdUserId(thirdUserId);
        queryBean.setType(type);
        SysThirdUser sysThirdUser = super.getOne(queryBean);
        return sysThirdUser != null ? sysThirdUser.getUserId() : null;
    }

    /**
     * 保存gitee用户
     * @param giteeUserInfo
     * @return 返回sysUserId
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer addGiteeUser(GiteeUserInfo giteeUserInfo){
        String giteeUserId = String.valueOf(giteeUserInfo.getId());
        String username = giteeUserInfo.getLogin();
        String nickname = giteeUserInfo.getName();
        if(StringUtils.isBlank(nickname)){
            nickname = username;
        }
        //保存到用户表
        //FIXME  这里的username取的是gitee的用户账号，目前没有考虑重复问题
        Integer userId = sysUserService.addUser(username, null, nickname);
        //保存到第三方用户表
        SysThirdUser sysThirdUser = new SysThirdUser();
        sysThirdUser.setUserId(userId);
        sysThirdUser.setThirdUserId(giteeUserId);
        sysThirdUser.setType(LoginType.GITEE.name());
        super.save(sysThirdUser);
        return userId;
    }


}
